import axios from 'axios'
import { stringify } from 'querystring'
import config from '../../config/config.js'

const excludeUrls = [
  "/faqbot/prompt",
  "/kgassist/move/search",
  "/kgassist/read",
]
const matchedRegExp = new RegExp(excludeUrls.join('|'))

export const init = () => {
  axios.defaults.baseURL = config.apiUrl
  axios.defaults.headers.post['Content-Type'] = 'application/json'

  axios.interceptors.request.use(req => {
    console.log('request', req)
    let { _loading }: any = window
    if (!req.url.match(matchedRegExp)) {
      _loading.show()
    }
    return req
  }, error => {
    let { _loading }: any = window
    _loading.hide()
    throw (error)
  })

  axios.interceptors.response.use(res => {
    console.log('request data', res)
    let { _loading }: any = window
    _loading.hide()
    return res.data
  }, error => {
    let { _loading, _toast }: any = window
    _loading.hide()
    _toast.show('接口请求错误', 'ErrorBadge')
    // setTimeout(() => {
    //   _toast.hide()
    // }, 3000)
    // 判断接口是否使用全局处理方式
    throw (error)
  })
}

const createRequest = (type) => {
  return (url, opts?: any) => {
    console.log('url', url, ' ,opts: ', opts)
    let { contentType, ...rest } = opts

    if (contentType === 2) {  //
      return axios[type](url, rest,
        {
          baseURL: config.apiUrl,
          headers: { ['Content-Type']: 'application/x-www-form-urlencoded' },
          transformRequest: [function (data, headers) {
            // Do whatever you want to transform the data
            return stringify(data);
          }],
        })
    }

    if (type === 'put' || type === 'post') {
      return axios[type](url, rest, { baseURL: config.apiUrl })
    } else {
      return axios[type](url, { baseURL: config.apiUrl, ...rest })
    }
  }
}

const withAxios = {
  get: createRequest('get'),
  post: createRequest('post'),
  put: createRequest('put'),
  delete: createRequest('delete'),
  axios
}

export default withAxios
